const express = require('express');
const router = express.Router();
const { User } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { BadRequest, NotFound } = require('http-errors');
const bcrypt = require('bcryptjs');

/**
 * 公共方法：查询当前用户
 * @param req
 * @param showPassword
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
const getUser = async (req, showPassword = false) => {
  const id = req.user.id;
  let condition = {};
  if (!showPassword) {
    condition = {
      attributes: { exclude: ['password'] },
    };
  }
  const user = await User.findByPk(id, condition);
  if (!user) {
    throw new NotFound(`ID: ${id}的用户未找到。`);
  }

  return user;
};

/**
 * 查询当前登录用户信息
 * GET /web/users/info
 */
router.get('/info', async function (req, res) {
  try {
    const user = await getUser(req);
    success(res, '查询当前用户信息成功。', user);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新用户信息
 * PUT /web/users/info
 */
router.put('/info', async (req, res) => {
  try {
    const body = {
      nickname: req.body.nickname,
      sex: req.body.sex,
      company: req.body.company,
      introduce: req.body.introduce,
      avatar: req.body.avatar,
    };

    const user = await getUser(req);
    await user.update(body);
    success(res, '更新用户信息成功。', { user });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新用户密码
 * PUT /web/users/password
 */
router.put('/password', async (req, res) => {
  const { password, newPassword, newPasswordConfirm } = req.body;
  try {
    if (!password) {
      throw new BadRequest('当前密码必须填写。');
    }

    if (newPassword !== newPasswordConfirm) {
      throw new BadRequest('两次输入的密码不一致。');
    }

    // 加上 true 参数，可以查询到加密后的密码
    const user = await getUser(req, true);

    // 验证当前密码是否正确
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      throw new BadRequest('当前密码不正确。');
    }

    await user.update({ password: newPassword });

    // 删除密码
    delete user.dataValues.password;
    success(res, '更新账户信息成功。', { user });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
